package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.CategoryHolder;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 每次登录都需要状态验证
 * @author zsk
 * @create 2022-02-14-10:20
 */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 查看session中是否有我们指定的用户对象
        Employee employee = (Employee) request.getSession().getAttribute("SESSION_EMPLOYEE");

        if (employee != null) {

            // 代表session存在,也就是用户处于登录状态，放行
            //将当前访问用户信息放入到ThreadLocal中
            EmployeeHolder.set(employee);
            return true;
        } else {
            //代表session不存在,
            //告诉前端页面,当前用户未登录
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);

            // 3-2禁止通行
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除ThreadLocal中当前线程的信息
        EmployeeHolder.remove();
        CategoryHolder.remove();

    }
}
